package siwi.map.android;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kankan.wheel.widget.NumericWheelAdapter;
import kankan.wheel.widget.WheelView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.wmw.Animation.ViewAction;
import com.wmw.DataPool.OrdersForm;
import com.wmw.Utility.Common;
import com.wmw.Utility.Dish;
import com.wmw.Utility.MSG;
import com.wmw.Utility.RegularExpression;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import siwi.map.android.History.ExAdapter;
import siwi.map.android.History.ExAdapter.Holder;
import siwi.map.android.R;

public class DishDetail extends SherlockActivity {
	// 1.4.0以上的手机有个设置-》开发-》不保留活动，有这样一个选项。只要勾选了它，activity一旦离开系统会自己将它清除：http://hi.baidu.com/xiaoxuevip/item/bc98d7f1bb31b412ff358240

	// private ActionBar mActionBar;
	private final Handler mHandler = new Handler();

	private TextView _positiveComment, _moderateComment, _negativeComment;
	private InputBox _price, _name;

	// Sale states.
	private ImageView _forSaleCheck, _toBeSoldOutCheck, _soldOutCheck;
	private Button _forSale, _toBeSoldOut, _soldOut;

	private WheelView _leftNum;
	private Button _leftView, _partView;

	Dish.DishSalesState _curSaleState;

	private Dish _dish;
	private ArrayList<Comments> _commentList = new ArrayList<Comments>();
	private ExAdapter adapter;

	private PullDownView pullListView;
	private ProgressBar moreProgressBar;
	private ScrollOverListView listView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initActionBar();

		setContentView(R.layout.dish_detail);
		
        initListView();
        
		_positiveComment = (TextView) findViewById(R.id.ODD_PositiveComment);
		_moderateComment = (TextView) findViewById(R.id.O_D_D_ModerateComment);
		_negativeComment = (TextView) findViewById(R.id.O_D_D_NegativeComment);

		// For sale.
		_forSale = (Button) findViewById(R.id.ODD_ForSale);
		_forSaleCheck = (ImageView) findViewById(R.id.ODD_ForSaleCheck);

		_forSale.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setForSaleState();
			}
		});

		// To be sold out.
		_leftNum = (WheelView) findViewById(R.id.ODD_LeftNum);
		_leftNum.setAdapter(new NumericWheelAdapter(1, 100, "%02d"));
		_leftNum.setLabel("");
		_leftNum.setCyclic(true);
		_leftView = (Button) findViewById(R.id.ODD_LeftView);
		_partView = (Button) findViewById(R.id.ODD_PartView);
		_toBeSoldOut = (Button) findViewById(R.id.ODD_ToBeSoldOut);

		_toBeSoldOut.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setToBeSoldOutState();
			}
		});

		// Sold out.
		_soldOut = (Button) findViewById(R.id.ODD_SoldOut);
		_soldOutCheck = (ImageView) findViewById(R.id.ODD_SoldOutCheck);

		_soldOut.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setSoldOutState();
			}
		});

		// Delete this dish.
		findViewById(R.id.DD_Delete).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.putExtra("Orders", "DishDetail");
				intent.putExtra("DishDetail", MSG.DeleteThisDish);
				setResult(Orders._MODIFY_DATA_OK, intent);
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
				finish();
			}

		});

		EditText etName = (EditText) findViewById(R.id.O_D_D_Name);
		ImageView ivClearName = (ImageView) findViewById(R.id.ODD_ClearName);
		_name = new InputBox(this, etName, ivClearName, null,
				etName.getPaddingRight(), RegularExpression.Normal, null);

		EditText etPrice = (EditText) findViewById(R.id.O_D_D_Price);
		ImageView ivClearPrice = (ImageView) findViewById(R.id.O_D_D_ClearPrice);
		_price = new InputBox(this, etPrice, ivClearPrice, null,
				etPrice.getPaddingRight(), RegularExpression.Fare, null);

		pullListView = (PullDownView) findViewById(R.id.pullListView);
		adapter = new ExAdapter(DishDetail.this);

		final View pcl = findViewById(R.id.ODD_PositiveCommentLine);
		final View mcl = findViewById(R.id.ODD_ModerateCommentLine);
		final View ncl = findViewById(R.id.ODD_NegativeCommentLine);

		LinearLayout pcll = (LinearLayout) findViewById(R.id.ODD_PositiveCommentLinearLayout);
		pcll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				_positiveComment.setTextColor(getResources().getColor(
						R.color.Blue));
				_moderateComment.setTextColor(getResources().getColor(
						R.color.Black));
				_negativeComment.setTextColor(getResources().getColor(
						R.color.Black));
				pcl.setVisibility(View.VISIBLE);
				mcl.setVisibility(View.INVISIBLE);
				ncl.setVisibility(View.INVISIBLE);
			}
		});

		LinearLayout mcll = (LinearLayout) findViewById(R.id.ODD_ModerateCommentLinearLayout);
		mcll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				_positiveComment.setTextColor(getResources().getColor(
						R.color.Black));
				_moderateComment.setTextColor(getResources().getColor(
						R.color.Blue));
				_negativeComment.setTextColor(getResources().getColor(
						R.color.Black));
				pcl.setVisibility(View.INVISIBLE);
				mcl.setVisibility(View.VISIBLE);
				ncl.setVisibility(View.INVISIBLE);
			}
		});

		LinearLayout ncll = (LinearLayout) findViewById(R.id.ODD_NegativeCommentLinearLayout);
		ncll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				_positiveComment.setTextColor(getResources().getColor(
						R.color.Black));
				_moderateComment.setTextColor(getResources().getColor(
						R.color.Black));
				_negativeComment.setTextColor(getResources().getColor(
						R.color.Blue));
				pcl.setVisibility(View.INVISIBLE);
				mcl.setVisibility(View.INVISIBLE);
				ncl.setVisibility(View.VISIBLE);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();

		_dish = (Dish) getIntent().getSerializableExtra(MSG.Dish);
		Dish.DishSalesState saleState = _dish.getSaleState();
		switch (saleState) {
		case FOR_SALE:
			setForSaleState();
			break;

		case SOLD_OUT:
			setSoldOutState();
			break;

		case LEFT_A_FEW:
			setToBeSoldOutState();
			break;

		default:
			Log.e(Common.GetLineInfo(), "Unexpected error!");
			break;
		}

		this._name.setContent(_dish.getName());
		this._price.setContent(Float.toString(_dish.getPrice()));
		this._leftNum.setCurrentItem(_dish.getLeftNum());
		this._positiveComment.setText("好评(" + _dish.getPositiveCommentsCnt()
				+ ")");
		this._moderateComment.setText("中评(" + _dish.getModerateCommentsCnt()
				+ ")");
		this._negativeComment.setText("差评(" + _dish.getNegativeCommentsCnt()
				+ ")");
		if (_dish != null) {
			refreshViews(_dish);
			Log.d(Common.GetLineInfo(),
					"Sale state -" + saleState + "P -"
							+ _dish.getPositiveCommentsCnt() + ", M -"
							+ _dish.getModerateCommentsCnt() + ", N -"
							+ _dish.getNegativeCommentsCnt());
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			goBack();
		}

		return super.onKeyDown(keyCode, event);
	}

	private void initActionBar() {
		// Custom action bar.
		ActionBar actionBar = getSupportActionBar();
		ActionBar.LayoutParams params = new ActionBar.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
				Gravity.CENTER);
		View view = LayoutInflater.from(this).inflate(
				R.layout.action_bar_back_save, null);
		actionBar.setCustomView(view, params);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);

		TextView tv = (TextView) view.findViewById(R.id.ABBS_Title);
		tv.setText("菜单详细信息");
		

		findViewById(R.id.ABBS_Back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewAction.startSpringMenuAnimations(v);
				// Go back.
				Log.d(Common.GetLineInfo(), "Go back without saving");
				goBack();
				return;
			}

		});

		findViewById(R.id.ABBS_Save).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewAction.startSpringMenuAnimations(v);
				if (!_name.isValide()) {
					Toast.makeText(DishDetail.this, "请输入正确的菜名",
							Toast.LENGTH_SHORT).show();
					return;
				} else if (!_price.isValide()) {
					Toast.makeText(DishDetail.this, "请输入正确的价格",
							Toast.LENGTH_SHORT).show();
					return;
				}

				Log.d(Common.GetLineInfo(), "Go back and saving");
				Intent intent = new Intent();
				intent.putExtra("Orders", "DishDetail"); // Send flag.
				intent.putExtra("DishDetail", MSG.ModifyThisDish);
				intent.putExtra(MSG.DishName, _name.getContent());
				intent.putExtra(MSG.DishPrice,
						Float.parseFloat(_price.getContent()));
				intent.putExtra(MSG.DishSaleState, _curSaleState);
				if (_curSaleState == Dish.DishSalesState.LEFT_A_FEW)
					intent.putExtra(MSG.DishLeftNum, _leftNum.getCurrentItem());
				// intent.setClass(DishDetail.this, MainTable.class);
				// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				// startActivity(intent);
				setResult(Orders._MODIFY_DATA_OK, intent);

				overridePendingTransition(R.anim.left_in, R.anim.right_out);

				finish();
				return;
			}
		});
	}

	private void initListView(){
        pullListView = (PullDownView) findViewById(R.id.pullListView);
        pullListView.enableAutoFetchMore(true, 0);
        listView = pullListView.getListView();
        adapter = new ExAdapter(DishDetail.this);
        listView.setAdapter(adapter);
        
        initArrays(new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		_commentList = (ArrayList<Comments>) msg.obj;
        		adapter.notifyDataSetChanged();
        		pullListView.notifyDidDataLoad(false);
        	}
        });
        
        pullListView.setOnPullDownListener(new PullDownView.OnPullDownListener() {
			
			@Override
			public void onRefresh() {
				getNewString(new Handler(){
					@Override
					public void handleMessage(Message msg) {
						addComments(3);
						adapter.notifyDataSetChanged();
						pullListView.notifyDidRefresh(_commentList.isEmpty());
					}
				});
			}
			
			@Override
			public void onLoadMore() {
				getNewString(new Handler(){
					@Override
					public void handleMessage(Message msg) {
						addComments(7);
						adapter.notifyDataSetChanged();
						pullListView.notifyDidLoadMore(_commentList.isEmpty());
					}
				});
			}
		});
	}

	private void initArrays(final Handler handler) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(3000);
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}

				addComments(10);
				
				
				handler.obtainMessage(0, _commentList).sendToTarget();
			}
		}).start();
	}
	private void getNewString(final Handler handler) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (Exception e) {
					Thread.interrupted();
					e.printStackTrace();
				}
				handler.obtainMessage(0, "New Text " + System.currentTimeMillis()).sendToTarget();
			}
		}).start();
	}
	private void goBack() {
		Intent intent = new Intent();
		intent.setClass(DishDetail.this, Home.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(intent);
		overridePendingTransition(R.anim.left_in, R.anim.right_out);
		DishDetail.this.finish();
	}

	private void setForSaleState() {
		this._leftNum.setVisibility(View.INVISIBLE);
		this._leftView.setVisibility(View.INVISIBLE);
		this._partView.setVisibility(View.INVISIBLE);
		this._forSaleCheck.setVisibility(View.VISIBLE);
		this._toBeSoldOut.setVisibility(View.VISIBLE);
		this._soldOutCheck.setVisibility(View.INVISIBLE);

		this._curSaleState = Dish.DishSalesState.FOR_SALE;
	}

	private void setToBeSoldOutState() {
		this._leftNum.setVisibility(View.VISIBLE);
		this._leftNum.setCurrentItem(0);
		this._leftView.setVisibility(View.VISIBLE);
		this._partView.setVisibility(View.VISIBLE);
		this._forSaleCheck.setVisibility(View.INVISIBLE);
		this._toBeSoldOut.setVisibility(View.INVISIBLE);
		this._soldOutCheck.setVisibility(View.INVISIBLE);

		this._curSaleState = Dish.DishSalesState.LEFT_A_FEW;
	}

	private void setSoldOutState() {
		this._leftNum.setVisibility(View.INVISIBLE);
		this._leftView.setVisibility(View.INVISIBLE);
		this._partView.setVisibility(View.INVISIBLE);
		this._forSaleCheck.setVisibility(View.INVISIBLE);
		this._toBeSoldOut.setVisibility(View.VISIBLE);
		this._soldOutCheck.setVisibility(View.VISIBLE);

		this._curSaleState = Dish.DishSalesState.SOLD_OUT;
	}

	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", "G1");
		map.put("info", "google 1");
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "G2");
		map.put("info", "google 2");
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "G3");
		map.put("info", "google 3");
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "G3");
		map.put("info", "google 3");
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", "G3");
		map.put("info", "google 3");
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", "G3");
		map.put("info", "google 3");
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", "G3");
		map.put("info", "google 3");
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", "G3");
		map.put("info", "google 3");
		list.add(map);
		return list;
	}

	private void refreshViews(Dish dish) {
		_positiveComment.setText("好评" + "(" + dish.getPositiveCommentsCnt()
				+ ")");
		_moderateComment.setText("中评" + "(" + dish.getModerateCommentsCnt()
				+ ")");
		_negativeComment.setText("差评" + "(" + dish.getNegativeCommentsCnt()
				+ ")");
	}

	private void addComments(int n){
		// TODO
		ExApplication app = (ExApplication)getApplication();
		SQLiteDatabase db = app._openDBHelper.getReadableDatabase();
		if (app._ordersData.isDishInDB(db, _dish.getName()) ){
			int id = app._ordersData.getDishID(db, _dish.getName());
			
			for (int i = 0; i < n; i++) {
				_commentList.add(new Comments("好难吃",
						"2013-12-33 10:31",
						COMMENT_LEVEL._NEGATIVE_COMMENT, id));
				}
		}
	}
	private enum COMMENT_LEVEL {
		_POSITIVE_COMMENT, _MODERATE_COMMENT, _NEGATIVE_COMMENT
	}

	private class Comments {
		private String _content;
		private String _date;
		private COMMENT_LEVEL _commentLevel;
		private int _belongDishID;

		public Comments(String comment, String date, COMMENT_LEVEL level, int belongDishID) {
			_content = comment;
			_date = date;
			_commentLevel = level;
			_belongDishID = belongDishID;
		}

		public String get_content() {
			return _content;
		}

		public void set_content(String _content) {
			this._content = _content;
		}

		public int get_belongDishID() {
			return _belongDishID;
		}

		public void set_belongDishID(int _belongDishID) {
			this._belongDishID = _belongDishID;
		}

		public String get_date() {
			return _date;
		}

		public void set_date(String _date) {
			this._date = _date;
		}

		public COMMENT_LEVEL get_commentLevel() {
			return _commentLevel;
		}

		public void set_commentLevel(COMMENT_LEVEL _commentLevel) {
			this._commentLevel = _commentLevel;
		}
	}

	private class ExAdapter extends BaseAdapter {
		private Context mContext;

		public ExAdapter(Context context) {
			mContext = context;
		}

		public void refresh(ArrayList<Comments> list) {
			_commentList = list;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return _commentList.size();
		}

		@Override
		public Object getItem(int position) {
			return _commentList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(mContext);
				convertView = inflater.inflate(
						R.layout.dish_detail_comment_item, null);
				holder = new Holder();
				holder._comment = (TextView) convertView
						.findViewById(R.id.DDCI_Comment);
				holder._time = (TextView) convertView
						.findViewById(R.id.DDCI_Time);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			Comments c = _commentList.get(position);
			switch (c.get_commentLevel()) {
			case _POSITIVE_COMMENT:
				break;

			case _MODERATE_COMMENT:
				break;

			case _NEGATIVE_COMMENT:
				break;

			default:
				Log.e(Common.GetLineInfo(), "Unexpected error");
				break;
			}
			
			holder._comment.setText(c.get_content());
			holder._time.setText(c.get_date());
			return convertView;
		}

		class Holder {
			private TextView _comment, _time;
		}
	}
}